<template>
  <div class="myAside">
    <MyAside @clear="eventClear"></MyAside>
    <div class="myAsideContent">
      <div class="devise-content" v-if="isShow">
        <div class="title">你好，我是您的营销助理小源</div>
        <div class="list">
          <div class="lable">试试以下的例子：</div>
          <div class="rows">
            <div class="item-box" @click="handleClickRow(1)">
              <div class="name">广告文案</div>
              <div class="desc">告诉我产品，帮你写文案</div>
            </div>
            <div class="item-box" @click="handleClickRow(2)">
              <div class="name">小红书文案</div>
              <div class="desc">帮你写适合小红书的文案</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 聊天 -->
      <el-scrollbar class="chart" v-else>
        <!-- 自己 -->
        <div class="section">
          <img src="../../assets/img/userIcon.png" class="avatar" alt="" />
          <div class="info">
            <template v-if="answerType === 1">
              <div class="text">{{ conText }}</div>
            </template>
            <template v-if="answerType === 2">
              <div class="li">{{ askArray.task }}</div>
              <template v-for="(item, index) in askArray.rows" :key="index">
                <div class="li" v-if="item.name">
                  {{ item.name }}：{{ item.value }}
                </div>
              </template>
            </template>
          </div>
        </div>

        <!-- 机器人 -->
        <div class="section active">
          <img src="../../assets/img/answer.png" class="avatar" alt="" />
          <div class="info">
            <el-skeleton :rows="2" animated v-if="isLoading" />
            <template v-else>
              <div class="li" v-for="(item, index) in answerArray" :key="index">
                {{ item }}
              </div>
            </template>
          </div>
        </div>
      </el-scrollbar>

      <!-- 输入框 -->
      <div class="areaText">
        <!-- 初始化 -->
        <div class="normal" v-if="!isEdit">
          <EditPen class="icon" />
          <input
            v-model="inputQuestion"
            type="text"
            class="input"
            placeholder="试试输入“赛博朋克”、“心得感悟”，挑选指令模板"
            @keydown="handleKeyDown"
          />
          <div class="btn" @click="handleAddQuestion(1)"></div>
        </div>

        <!-- 编辑 -->
        <div class="multiple" v-if="isEdit">
          <EditPen class="icon" />
          <div class="cont">
            <div class="title" contenteditable="true">{{ write.task }}</div>
            <template v-if="write.rows.length > 0">
              <div
                class="item-box"
                v-for="(item, index) in write.rows"
                :key="index"
              >
                <div class="label" contenteditable="true" v-if="item.name">
                  {{ item.name }}：
                </div>
                <div class="value" v-if="item.value">
                  <div contenteditable="true" class="text">
                    {{ item.value }}
                  </div>
                </div>
              </div>
            </template>
          </div>
          <div class="btn" @click="handleAddQuestion(2)"></div>
        </div>
      </div>
    </div>
    <div class="colR">
      <div class="tools">
        <el-button
          type="primary"
          :icon="Plus"
          class="add"
          @click="handleAddRows"
          >新建</el-button
        >
        <el-input
          :prefix-icon="Search"
          :style="{ marginLeft: '12px' }"
        ></el-input>
      </div>
      <div class="tab">
        <div
          class="item"
          :class="{ active: query.type === '市场分析' }"
          @click="handleSearch('市场分析')"
        >
          市场分析
        </div>
        <div
          class="item"
          :class="{ active: query.type === '产品策划' }"
          @click="handleSearch('产品策划')"
        >
          产品策划
        </div>
        <div
          class="item"
          :class="{ active: query.type === '广告创意' }"
          @click="handleSearch('广告创意')"
        >
          广告创意
        </div>
        <div
          class="item"
          :class="{ active: query.type === '市场活动' }"
          @click="handleSearch('市场活动')"
        >
          市场活动
        </div>
        <div
          class="item"
          :class="{ active: query.type === '自媒文案' }"
          @click="handleSearch('自媒文案')"
        >
          自媒文案
        </div>
        <div
          class="item"
          :class="{ active: query.type === '学营销' }"
          @click="handleSearch('学营销')"
        >
          学营销
        </div>
      </div>
      <div class="list-content" v-if="planArray.length > 0">
        <div class="rows">
          <div class="item-box" v-for="(item, index) in planArray" :key="index">
            <div class="name" @click="handleSelect(item)">{{ item.name }}</div>
            <div class="desc">{{ item.introduction }}</div>
            <EditPen class="icon" @click="handleEdit(item)" />
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑' : '新增'"
      width="710px"
      draggable
      destroy-on-close
      @close="handleClose"
    >
      <el-form :model="form" ref="form2" labelWidth="100px" :rules="rules">
        <el-form-item label="Prompt名称" prop="name" :key="1">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="introduction" :key="2">
          <el-input v-model="form.introduction"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option value="市场分析"></el-option>
            <el-option value="产品策划"></el-option>
            <el-option value="广告创意"></el-option>
            <el-option value="市场活动"></el-option>
            <el-option value="自媒文案"></el-option>
            <el-option value="学营销"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="约束条件" prop="restrictions">
          <el-input
            type="textarea"
            :rows="6"
            v-model="form.restrictions"
          ></el-input>
        </el-form-item>
        <el-form-item label="任务" prop="task">
          <el-input v-model="form.task"></el-input>
        </el-form-item>
        <el-form-item label="输入项" prop="rows">
          <el-row type="flex" :style="{ marginBottom: '10px', width: '100%' }">
            <el-button type="primary" :icon="Plus" @click="handleAddItem"
              >添加</el-button
            >
          </el-row>
          <div :style="{ width: '100%' }">
            <el-table :data="form.rows">
              <el-table-column label="名称" width="150px" align="center">
                <template #default="data">
                  <el-input
                    v-model="data.row.name"
                    :style="{ width: '100%' }"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="示例" align="center">
                <template #default="data">
                  <el-input
                    v-model="data.row.value"
                    :style="{ width: '100%' }"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="70px">
                <template #default="data">
                  <el-button
                    :icon="Minus"
                    @click="handleMinusItem(data.$index)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <div class="btn-panel">
        <el-button type="primary" :loading="loading" @click="handleSave()"
          >确定</el-button
        >
        <el-button :loading="loading" @click="handleClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { reactive, ref, onMounted, onUnmounted } from "vue";
import { Plus, Search, EditPen, Minus } from "@element-plus/icons-vue";
import { GetPlanList, SavePlan, UpdatePlan } from "../../services/api.js";
import { PostEndpoint } from "../../services/gpt.js";
import { getmark } from "../../utils/watermark";
import MyAside from "./MyAside.vue";
const { watermark } = getmark();
const tabIndex = ref(0);
const isEdit = ref(false);
const dialogVisible = ref(false);
const form2 = ref("");
const inputQuestion = ref("");
const conText = ref("");
const loading = ref(false);
const answerType = ref(1);
let form = reactive({
  id: null,
  name: "",
  introduction: "",
  type: "",
  restrictions: "",
  task: "",
  input: "",
  rows: [],
});
const isShow = ref(true);
const askArray = ref({});
const answerArray = ref([]);
const query = reactive({
  name: "",
  introduction: "",
  type: "市场分析",
  constraint: "",
  task: "",
  input: "",
});
const isLoading = ref(false);

const write = ref({});

const planArray = ref([]);
const rules = reactive({
  name: [{ required: true, message: "请输入Prompt名称" }],
  introduction: [{ required: true, message: "请输入简介" }],
  type: [{ required: true, message: "请选择分类" }],
  restrictions: [{ required: true, message: "请输入约束条件" }],
  task: [{ required: true, message: "请输入任务" }],
  rows: [{ required: true, message: "请输入" }],
});

function initData() {
  GetPlanList(query).then(({ data }) => {
    planArray.value = data;
  });
}

function handleSearch(type) {
  query.type = type;
  initData();
}

function handleSave() {
  form2.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      if (form.id) {
        form.input = JSON.stringify(form.rows);
        UpdatePlan(form).then(() => {
          ElMessage.success("保存成功");
          handleClose();
          initData();
        });
      } else {
        form.input = JSON.stringify(form.rows);
        SavePlan(form).then(() => {
          ElMessage.success("保存成功");
          handleClose();
          initData();
        });
      }
    }
  });
}

function eventClear() {
  isShow.value = true;
  isEdit.value = false;
}

function handleSelect(row) {
  row.rows = JSON.parse(row.input);
  write.value = row;
  isEdit.value = true;
}

function handleEdit(row) {
  row.rows = JSON.parse(row.input);
  dialogVisible.value = true;
  form = row;
}

function handleClose() {
  form2.value.resetFields();
  dialogVisible.value = false;
  loading.value = false;
  initData();
}

function handleClickRow(type) {
  answerType.value = 2;
  isShow.value = false;
  isEdit.value = false;
  isLoading.value = true;
  if (type === 1) {
    askArray.value = {
      task: "你是奥美广告文案创意总监，请根据以下要求创作宣传语",
      rows: [
        {
          name: "产品名称",
          value: "酸奶麦香脆枣",
        },
        {
          name: "宣传语要求",
          value: "简洁有意境，突出产品的特点",
        },
        {
          name: "文案形式",
          value: "一句话文案",
        },
      ],
    };
  }
  if (type === 2) {
    askArray.value = {
      task: "你是一位擅长创作小红书爆款文章的专家，请根据以下要求撰写一篇文章:",
      rows: [
        {
          name: "文章主题",
          value: "蕾丝连衣裙",
        },
        {
          name: "创作要点",
          value:
            "标题运用二极管标题法吸引眼球，内容使用惊叹号、表情符号增加活力，运用悬念和刺激引发读者好奇心，融入热点话题，采用口语化表达，选择与标题和正文强相关的tags",
        },
        {
          name: "关键词",
          value: "仙气，淑女，婚纱感",
        },
        {
          name: "字数要求",
          value: "约500字",
        },
      ],
    };
  }
  setTimeout(() => {
    isLoading.value = false;
    if (type === 1) {
      answerArray.value = ["酸奶加脆枣，一口新鲜，唤醒舌尖的春天"];
    }
    if (type === 2) {
      answerArray.value = [
        "标题：【💥💥秒变仙女！这款蕾丝连衣裙，淑女风满满！👗👗】",
        "内容：亲们，你们知道吗？我最近发现了一款超级仙气的蕾丝连衣裙，穿上它，我瞬间感觉自己变成了童话里的公主！👑👑",
        "这款蕾丝连衣裙，设计独特，蕾丝装饰既浪漫又女人，而且裙摆飘逸，走起路来摇曳生姿，仿佛每一步都在跳舞。💃💃",
        "更让我惊喜的是，这款连衣裙还有一种婚纱的感觉，仿佛置身于婚礼现场，成为焦点。👰👰",
      ];
    }
  }, 3000);
}

function handleKeyDown(event) {
  if (event.keyCode === 13) {
    handleAddQuestion(1);
  }
}

const handleAddQuestion = (type) => {
  let str = [];
  if (type === 1) {
    if (inputQuestion.value.length === 0) {
      return ElMessage.error("请输入内容");
    }
    conText.value = inputQuestion.value;
    str = [conText.value];
    str = str.join("");
  } else {
    str = [write.value.task];
    write.value.rows.map((item) => {
      str.push(`${item.name}：${item.value}`);
    });
    str = str.join("\n");
  }
  inputQuestion.value = "";
  answerType.value = type;
  askArray.value = write.value;
  isLoading.value = true;
  isShow.value = false;
  isEdit.value = false;
  PostEndpoint({
    text: str,
  })
    .then((res) => {
      isLoading.value = false;
      answerArray.value = res.answer.split("\n\n");
    })
    .catch(() => {
      isLoading.value = false;
      answerArray.value = [
        "很抱歉，您的问题我无法回答，我还要多学习学习~",
        "感谢您的理解，谢谢！",
      ];
      write.value = {};
    });
};

const handleAddItem = () => {
  form.rows.push({
    name: "",
    value: "",
  });
};

const handleAddRows = () => {
  form.id = null;
  form.name = "";
  form.introduction = "";
  form.restrictions = "";
  form.task = "";
  form.rows = [];
  dialogVisible.value = true;
  console.log(form);
};

const handleMinusItem = (index) => {
  form.rows.splice(index, 1);
};

onMounted(() => {
  initData();
  watermark("源食引擎");
});

onUnmounted(() => {
  watermark("");
});
</script>

<style lang="scss" scoped>
.myAside {
  height: 100%;
  width: 100%;
  display: flex;

  .myAsideContent {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #f4f4f4;
    border-left: solid 1px #eee;

    .devise-content {
      width: 86%;
      padding: 20px 0;
      clear: both;
      overflow: hidden;
      margin: 0 auto;

      .title {
        font-weight: bold;
      }

      .list {
        background-color: #f4f4ff;
        border-radius: 5px;
        clear: both;
        overflow: hidden;
        padding: 12px;
        margin-top: 12px;

        .rows {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;

          .item-box {
            width: calc(50% - 30px);
            background-color: #fff;
            border-radius: 4px;
            padding: 12px;
            margin-top: 12px;
            cursor: pointer;

            .name {
              color: #3838b6;
              font-weight: bold;
            }

            .desc {
              color: #999;
              margin-top: 8px;
              font-size: 12px;
            }
          }
        }
      }
    }

    .chart {
      clear: both;
      width: 86%;
      margin: 0 auto 20px;

      .section {
        display: flex;
        padding: 18px;
        border-radius: 12px;
        margin-top: 10px;

        .avatar {
          width: 32px;
          height: 32px;
          border-radius: 50%;
        }

        .info {
          flex: 1;
          width: 1%;
          margin-left: 12px;

          .li {
            line-height: 24px;
          }

          .text {
            line-height: 32px;
          }
        }

        &.active {
          background-color: #fff;

          .info {
            .li {
              padding: 5px 0;
            }
          }
        }
      }
    }

    .areaText {
      width: calc(86% - 2px);
      background-color: #fff;
      border-radius: 10px;
      border: solid 1px #ddd;
      margin: auto auto 20px;

      .normal {
        height: 60px;
        display: flex;
        align-items: center;

        .icon {
          width: 24px;
          height: 24px;
          font-size: 24px;
          margin-left: 15px;
          color: #999;
        }

        .input {
          color: #999;
          font-size: 16px;
          flex: 1;
          width: 1%;
          border-style: none;
          border-width: 0;
          outline-style: none;
          outline-width: 0;
          height: 40px;
          margin-left: 12px;
        }

        .btn {
          width: 45px;
          height: 45px;
          background: url("../../assets/img/send.png") no-repeat center;
          background-size: auto 45px;
          border-radius: 50%;
          margin-right: 12px;
          cursor: pointer;
          transition: 300ms;
        }
      }

      .multiple {
        display: flex;
        align-items: flex-start;

        .icon {
          width: 24px;
          height: 24px;
          font-size: 24px;
          margin-left: 15px;
          margin-top: 12px;
          color: #999;
        }

        .cont {
          flex: 1;
          padding: 10px 12px 8px;

          &:focus {
            outline-style: none;
          }

          .title {
            line-height: 28px;
            font-size: 16px;
            padding: 2px 0 5px;
          }

          .item-box {
            display: flex;
            padding: 5px 0;

            .label {
              font-size: 16px;
              line-height: 28px;

              &:focus {
                outline: 0;
              }
            }

            .value {
              width: 1%;
              flex: 1;

              .text {
                font-size: 16px;
                line-height: 28px;
                background-color: #f4f4ff;
                padding: 0 5px;
                border-radius: 5px;
                word-break: break-word;
                white-space: pre-wrap;
                display: inline-block;
                cursor: pointer;

                &:focus {
                  background-color: #fff;
                  outline-color: #3838b6;
                }
              }
            }
          }
        }

        .btn {
          width: 45px;
          height: 45px;
          background: url("../../assets/img/send.png") no-repeat center;
          background-size: auto 45px;
          border-radius: 50%;
          margin-right: 12px;
          margin-bottom: 5px;
          cursor: pointer;
          align-self: end;
          transition: 300ms;
        }
      }
    }
  }

  .colR {
    width: 438px;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    padding-left: 12px;

    .tools {
      display: flex;
      align-items: center;
      padding: 12px 12px 12px 0;

      .add {
        background-color: #e5eefd;
        color: #2171fe;
      }
    }

    .tab {
      display: flex;
      flex-wrap: wrap;

      .item {
        background-color: #f5f5f5;
        height: 32px;
        padding: 0 9px;
        margin: 0 12px 12px 0;
        border-radius: 5px;
        display: flex;
        align-items: center;
        cursor: pointer;

        &.active {
          background-color: #2171fe;
          color: #fff;
        }
      }
    }

    .list-content {
      overflow: hidden;
      overflow-y: auto;

      &::-webkit-scrollbar {
        width: 0;
        height: 0;
      }

      .rows {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        padding: 0 12px 6px 0;

        .item-box {
          width: calc(50% - 30px);
          background-color: #f4f4ff;
          border-radius: 8px;
          margin: 6px 0;
          padding: 12px;
          cursor: pointer;
          transition: 300ms;
          position: relative;

          &:hover {
            background-color: #e9e9f9;
          }

          .name {
            font-weight: bold;
            cursor: pointer;
          }

          .desc {
            height: 40px;
            font-size: 12px;
            line-height: 20px;
            margin-top: 8px;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }

          .icon {
            width: 13px;
            height: 13px;
            font-size: 13px;
            position: absolute;
            right: 6px;
            bottom: 6px;
            cursor: pointer;
            color: #bbb;
          }
        }
      }
    }
  }

  .btn-panel {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 10px;
  }
}
</style>
